/**
 * 统一资源管理 API
 *
 * 基于统一资源模型（Resource）的API接口
 * 支持一切皆资源的理念，包括能力资源
 */

import type {
  AttributesFacet,
  BehaviorsFacet,
  CapabilityFacet,
  EventsFacet,
  LifecycleFacet,
  RelationsFacet,
  Resource,
  ResourceId,
  ResourceListResponse,
  ResourceQueryParams,
  VersionRecord,
  VersionsFacet,
} from './types';

import { mockRequestClient as requestClient } from '#/api/request';

// ==================== 基础 CRUD 操作 ====================

/**
 * 创建资源
 */
export const createResource = (resource: Partial<Resource>) =>
  requestClient.post<Resource>('/resources', resource);

/**
 * 获取资源详情
 */
export const getResource = (id: ResourceId) =>
  requestClient.get<Resource>(`/resource-center/resources/${id}`);

/**
 * 更新资源
 */
export const updateResource = (id: ResourceId, resource: Partial<Resource>) =>
  requestClient.put<Resource>(`/resource-center/resources/${id}`, resource);

/**
 * 删除资源（软删除/归档）
 */
export const deleteResource = (id: ResourceId) =>
  requestClient.delete(`/resource-center/resources/${id}`);

// ==================== 发布治理 ====================

/**
 * 发布资源（生成新版本并发布，支持灰度）
 */
export const publishResource = (id: ResourceId, options?: PublishOptions) =>
  requestClient.post<Resource>(
    `/resource-center/resources/${id}/publish`,
    options,
  );

/**
 * 回滚到指定版本
 */
export const rollbackResource = (id: ResourceId, version: string) =>
  requestClient.post<Resource>(`/resource-center/resources/${id}/rollback`, {
    version,
  });

/**
 * 获取历史版本列表
 */
export const getResourceVersions = (id: ResourceId) =>
  requestClient.get<VersionRecord[]>(
    `/resource-center/resources/${id}/versions`,
  );

// ==================== 子接口更新 ====================

/**
 * 更新属性包
 */
export const updateResourceAttributes = (
  id: ResourceId,
  attributes: AttributesFacet,
) =>
  requestClient.put<Resource>(
    `/resource-center/resources/${id}/facets/attributes`,
    attributes,
  );

/**
 * 更新生命周期/状态机
 */
export const updateResourceLifecycle = (
  id: ResourceId,
  lifecycle: LifecycleFacet,
) =>
  requestClient.put<Resource>(
    `/resource-center/resources/${id}/facets/lifecycle`,
    lifecycle,
  );

/**
 * 更新行为定义
 */
export const updateResourceBehaviors = (
  id: ResourceId,
  behaviors: BehaviorsFacet,
) =>
  requestClient.put<Resource>(
    `/resource-center/resources/${id}/facets/behaviors`,
    behaviors,
  );

/**
 * 更新事件配置
 */
export const updateResourceEvents = (id: ResourceId, events: EventsFacet) =>
  requestClient.put<Resource>(
    `/resource-center/resources/${id}/facets/events`,
    events,
  );

/**
 * 更新关系配置
 */
export const updateResourceRelations = (
  id: ResourceId,
  relations: RelationsFacet,
) =>
  requestClient.put<Resource>(
    `/resource-center/resources/${id}/facets/relations`,
    relations,
  );

/**
 * 更新能力配置
 */
export const updateResourceCapability = (
  id: ResourceId,
  capability: CapabilityFacet,
) =>
  requestClient.put<Resource>(
    `/resource-center/resources/${id}/facets/capability`,
    capability,
  );

/**
 * 更新版本配置
 */
export const updateResourceVersions = (
  id: ResourceId,
  versions: VersionsFacet,
) =>
  requestClient.put<Resource>(
    `/resource-center/resources/${id}/facets/versions`,
    versions,
  );

// ==================== 运行时操作 ====================

/**
 * 执行状态迁移
 */
export const transitionResourceState = (
  id: ResourceId,
  transition: StateTransition,
) =>
  requestClient.post<Resource>(
    `/resource-center/resources/${id}/state/transition`,
    transition,
  );

/**
 * 执行行为
 */
export const invokeResourceBehavior = (
  id: ResourceId,
  behaviorId: string,
  invocation: BehaviorInvocation,
) =>
  requestClient.post<any>(
    `/resource-center/resources/${id}/behaviors/${behaviorId}/invoke`,
    invocation,
  );

// ==================== 查询与搜索 ====================

/**
 * 搜索资源
 */
export const searchResources = (params: ResourceQueryParams) =>
  requestClient.get<ResourceListResponse>('/resource-center/resources', {
    params,
  });

/**
 * 获取资源关系图
 */
export const getResourceGraph = (id: ResourceId) =>
  requestClient.get<any>(`/resource-center/resources/${id}/graph`);

/**
 * 获取资源历史
 */
export const getResourceHistory = (id: ResourceId, facet?: string) =>
  requestClient.get<any[]>(`/resource-center/resources/${id}/history`, {
    params: { facet },
  });

// ==================== 批量操作 ====================

/**
 * 批量发布资源
 */
export const batchPublishResources = (
  ids: ResourceId[],
  options?: PublishOptions,
) =>
  requestClient.post<Resource[]>('/resource-center/resources/batch/publish', {
    ids,
    options,
  });

/**
 * 批量下线资源
 */
export const batchDeactivateResources = (ids: ResourceId[]) =>
  requestClient.post<Resource[]>(
    '/resource-center/resources/batch/deactivate',
    { ids },
  );

/**
 * 批量移动标签
 */
export const batchMoveResourceLabels = (
  ids: ResourceId[],
  labels: Record<string, string>,
) =>
  requestClient.post<Resource[]>('resource-center/resources/batch/labels', {
    ids,
    labels,
  });

// ==================== 类型定义 ====================

/**
 * 状态迁移参数
 */
export interface StateTransition {
  to: string;
  cause?: string;
  context?: any;
}

/**
 * 行为调用参数
 */
export interface BehaviorInvocation {
  input: any;
  traceId?: string;
}

/**
 * 发布选项
 */
export interface PublishOptions {
  strategy?: 'ALL_AT_ONCE' | 'BATCH' | 'BLUE_GREEN' | 'CANARY';
  segments?: Array<{ filter?: any; percentage: number }>;
  startAt?: string;
  freezeWindow?: { from: string; to: string };
}

// ==================== 导出 ====================

export const resourceApi = {
  // 基础 CRUD
  create: createResource,
  get: getResource,
  update: updateResource,
  delete: deleteResource,

  // 发布治理
  publish: publishResource,
  rollback: rollbackResource,
  getVersions: getResourceVersions,

  // 子接口更新
  updateAttributes: updateResourceAttributes,
  updateLifecycle: updateResourceLifecycle,
  updateBehaviors: updateResourceBehaviors,
  updateEvents: updateResourceEvents,
  updateRelations: updateResourceRelations,
  updateCapability: updateResourceCapability,
  updateVersions: updateResourceVersions,

  // 运行时操作
  transitionState: transitionResourceState,
  invokeBehavior: invokeResourceBehavior,

  // 查询
  search: searchResources,
  getGraph: getResourceGraph,
  getHistory: getResourceHistory,

  // 批量操作
  batchPublish: batchPublishResources,
  batchDeactivate: batchDeactivateResources,
  batchMoveLabels: batchMoveResourceLabels,
};
